package com.scientificInfo.controller;

import com.scientificInfo.bean.*;
import com.scientificInfo.dto.UpdatePasswordDto;
import com.scientificInfo.entity.TSMResult;
import com.scientificInfo.server.TeacherServer;
import com.scientificInfo.server.UserServer;
import com.scientificInfo.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserServer userServer;

    @Autowired
    TeacherServer teacherServer;

    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";
    private static final String DOWNLOAD_DIRECTORY = "download";

    // 上传配置
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    //登录
    @RequestMapping("/login")
    @ResponseBody
    public Map checkLogin(@RequestBody(required = false) User user, HttpSession session) {

        Map<String, Object> map = new HashMap<>();
        TSMResult tsmResult = new TSMResult();
        String inputId = user.getUserId();
        String inputPaswd = user.getUserPaswd();

        boolean flag = userServer.checkUser(inputId);
        if (!flag) {
            tsmResult.setCode(200);
            tsmResult.setMessage("不存在的用户名!");
            map.put("tsmResult", tsmResult);
        } else {
            String paswd = userServer.getUserById(user).getUserPaswd();
            if (!paswd.equals(inputPaswd)) {
                tsmResult.setCode(200);
                tsmResult.setMessage("对不起，用户名或密码错误！");
                tsmResult.setData(0);
                map.put("tsmResult", tsmResult);
            } else {
                //如果存在 并且密码没错误
                // 但是如果该用户是教师 并且该教师已被注销
                // 应该叫教师去联系管理员
                List<Teacher> list = teacherServer.selectTeacherById(user.getUserId());

                //如果是教师
                if (list.size() > 0) {
                    Teacher teacher = list.get(0);
                    Integer teacherStatus = teacher.getTeacherstatu();

                    //1代表激活 2代表注销
                    if (teacherStatus == 2) {
                        tsmResult.setCode(200);
                        tsmResult.setMessage("您好，您已被注销，请及时与管理员联系!");
                        tsmResult.setData(teacherStatus);
                        map.put("tsmResult", tsmResult);
                        return map;
                    }
                }
                //对于相应资源 有必要存入session中
                String jwt = jwtUtils.generateToken(user.getUserId());
                map.put("token", jwt);
                user = userServer.getUserById(user);
                //登录即登录次数加一
                userServer.checkUserCountNum(user);
                tsmResult.setMessage("登录成功!");
                tsmResult.setCode(200);
                user.setUserPaswd("whatdoyouthink");
                tsmResult.setData(user);
                map.put("tsmResult", tsmResult);
            }
        }
        return map;
    }

    //暂时没用
    @RequestMapping("/mainpage")
    public String toMainPage(String Id, Model model) {
        model.addAttribute("Id", Id);
        model.addAttribute("SystemMsg", userServer.selectMsgToAllTeacher());
        model.addAttribute("PersonMsg", userServer.selectMsgToTeacher(Id));
        return "/teacher/teacher.jsp";
    }

    //暂时没用
    @RequestMapping("/logout")
    @ResponseBody
    public TSMResult logout(HttpSession session) {
        TSMResult tsmResult = new TSMResult();
        session.removeAttribute("id_infor");
        tsmResult.setMessage("注销成功！");
        return tsmResult;
    }

    //更改密码
    @PostMapping("/updatePassword")
    @ResponseBody//password 改为 newPassword
    public TSMResult updatePassword(@RequestBody(required = false) UpdatePasswordDto updatePasswordDto, HttpSession session, TSMResult tsmResult) {
        tsmResult.setCode(200);
        tsmResult.setMessage("密码更改成功，请重新登录！");
        String username = updatePasswordDto.getUsername();
        String password = updatePasswordDto.getNewPassword();
        int result = userServer.updatePassword(username, password);
        tsmResult.setData(result);
        return tsmResult;
    }

    //下载论文
    @RequestMapping(value = "/DownloadServlet")
    public ResponseEntity<byte[]> fileDownload(
            HttpServletRequest request,
            @RequestParam("paperName") String fileName,
            Model model) throws Exception {
        fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8"); //后台接受中文数据编码
        fileName = fileName + ".doc";

        String filePath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY + "\\" + fileName;
        System.out.println(filePath);
        File file = new File(filePath);

        HttpHeaders headers = new HttpHeaders();
        String downloadFile = new String(fileName.getBytes("utf-8"), "iso-8859-1");
        headers.setContentDispositionFormData("attachment", downloadFile);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

    //elementUI 上传方法
    @PostMapping(value = "/uploading")
    @ResponseBody
    public TSMResult uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request, TSMResult tsmResult) {

        if (file.isEmpty()) {
            tsmResult.setData(0);
            tsmResult.setMessage("文件不可为空！");
            return tsmResult;
        }
        // 获取文件全名a.py
        String fileName = file.getOriginalFilename();
        // 文件上传路径<br>        String templatePath = "E:/file/template/"
        String templatePath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;

        System.out.println("文件路径：" + templatePath);

        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        //获取文件名
        String prefixName = fileName.substring(0, fileName.lastIndexOf("."));
        // 解决中文问题,liunx 下中文路径,图片显示问题
        //fileName = UUID.randomUUID() + suffixName;
        File dest0 = new File(templatePath);
        //prefixName + File.separator +
        File dest = new File(dest0, fileName);


        //文件上传-覆盖
        try {
            // 检测是否存在目录
            if (!dest0.getParentFile().exists()) {
                dest0.getParentFile().mkdirs();
                //检测文件是否存在
            }
            if (!dest.exists()) {
                dest.mkdirs();
            }
            file.transferTo(dest);

            //上传成功后 将上传路径上传到数据库中
            String filePathSaved = templatePath + File.separator;
            teacherServer.saveFilePath(filePathSaved, fileName);

            tsmResult.setData(1);
            tsmResult.setMessage("文件上传成功！");
            return tsmResult;
        } catch (Exception e) {
            tsmResult.setData(0);
            tsmResult.setMessage("服务器错误，请稍后再试！");
            return tsmResult;
        }
    }

    //SpringMVC 上传文件
    @RequestMapping(value = "/UploadServlet", method = RequestMethod.POST)
    public String upload(
            ModelAndView modelAndView,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {


        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置最大文件上传值
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // 设置最大请求值 (包含文件和表单数据)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // 中文处理
        upload.setHeaderEncoding("UTF-8");

        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;

        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try {
            List<FileItem> formItems = upload.parseRequest(request);
            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);

                        // 在控制台输出文件的上传路径
                        String filePathSaved = uploadPath + File.separator;

                        // 保存文件到硬盘
                        item.write(storeFile);
                        teacherServer.saveFilePath(filePathSaved, fileName);
                        request.setAttribute("message", formItems.get(0).getName() + "文件上传成功!");
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message", "错误信息: " + "文件上传失败，请检查是否文件为空！");

        }
        return "/teacher/tea_add_paper";
    }

    //查询所有会议
    @RequestMapping("/show_meeting")
    @ResponseBody
    public Map showAllTheMeeting() {
        List<Meeting> list = teacherServer.selectAllMeeting();
        Map<String, Object> map = new HashMap<>();
        List<Meeting> meetingList = new ArrayList<>();  //大的List
        //根据每一个会议编号 去查询对应的人员
        for (Meeting meeting : list) {
            //查出来的是多个数据
            List<TakeMeeting> takeMeetingList = teacherServer.selectByMeetingId(meeting.getMeetingid()); //列中的List
            meeting.setTakeMeetingList(takeMeetingList);
            meetingList.add(meeting);
        }
        map.put("meetingList", meetingList);
        map.put("tsmResult", new TSMResult(200, "查询成功", list));
        return map;
    }


}
